<?php

namespace App\Services\Topic;

use App\Constants\CodeData;
use App\Dao\AnchorSortLogDao;
use App\Dao\AppUpgradeDao;
use App\Dao\ClosenessDao;
use App\Dao\FollowActionDao;
use App\Dao\SettingDao;
use App\Dao\TopicDao;
use App\Dao\TopicReplyDao;
use App\Dao\UserDao;
use App\Exception\MessageException;
use App\Model\Topic;
use App\Model\TopicZan;
use App\Services\Mission\MissionQueue;
use App\Utils\AliyunOssHelper;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use Hyperf\Context\Context;

class TopicService
{
    /**
     * Note - 推荐、或者关注用户的帖子列表
     * DateTime 2024/7/22 11:40
     * User Admin
     * @param $userInfo
     * @param $params
     * @return array
     */
    public function getTopicList($userInfo, $params)
    {
        $uid = $userInfo['id'];
        $page = $params['page'] ?? 1;
        $type = $params['type'] ?? 1;// 1-推荐; 2-关注
        $from = $params['from'];
        $version_code = $params['version_code'] ?? 1;
        $channel = $params['channel'] ?? 1;
        $pageSize = 10;
        $language = Context::get('language');

        if ($type == 2) {
            // 关注
            $idols = FollowActionDao::getInstance()->getIdolsIds($uid);
            if (empty($idols)) {
                throw new MessageException('您还没有关注任何用户', CodeData::SUCCESS);
            } else {
                // $where[] = ['topic.uid', 'in', $idols];
                $where[] = [function ($query) {
                    return $query->whereIn('topic.uid', [1, 2]);
                }];
            }
        }
        // 推荐
        if ($userInfo['super_noble'] == 1 || $userInfo['noble'] == 1) {
            $where[] = ['topic.show_type', '<>', 2];
        } else {
            $where[] = ['topic.show_type', '=', 0];
        }
        $where[] = ['topic.status', '=', 1];


        // 获取帖子/回帖列表
        if ((new AppUpgradeDao())->isHideCall($from, $version_code, $channel)) {
            $where[] = ['topic.in_audit', '=', 1];
        } else {
            $where[] = ['topic.in_audit', '=', 0];
            $where[] = ['u.isdel', '=', 0];

            if ($userInfo['sex'] == 1) {
                $where[] = ['u.sex', '=', 2];

            } else {
                $where[] = ['u.sex', '=', 1];
            }
        }


        $topic = topicDao::getInstance()->getConditionTopicList($uid, $where, $page, $pageSize, $version_code);
        empty($topic) && $topic = array();

        $uids = array_column($topic, "uid");
        $tease_arr = UserDao::getInstance()->readTease($uids, $uid);
        $cArr = ClosenessDao::getMyCloseness($uid, $userInfo['sex'], $uids);

        // 计算帖子发布时间
        // $time = time();
        if (!empty($topic)) {
            foreach ($topic as $k => &$v) {
                $v['is_tease'] = isset($tease_arr[$v['uid']]) ? 1 : 0;
                if (isset($cArr[$v['uid']]) && $cArr[$v['uid']] > 0) {
                    $v['is_tease'] = 1;
                }
                $topic[$k]['time_content'] = FunUtil::TopicPushTimeAgo($v['publish_time'], $language);
                // $t = ($time - (int)$v['publish_time']);
                // if ($t < 3600) {
                //     $t1 = ceil($t / 60);
                //     $topic[$k]['time_content'] = trans("message.分钟前", ['t' => $t1], $language);
                // } elseif ($t < 24 * 3600) {
                //     $t2 = ceil($t / 3600);
                //     $topic[$k]['time_content'] = trans("message.小时前", ['t' => $t2], $language);
                // } elseif ($t < 7 * 24 * 3600) {
                //     $t3 = ceil($t / 24 / 3600);
                //     $topic[$k]['time_content'] = trans("message.天前", ['t' => $t3], $language);
                // } elseif ($t < 21 * 24 * 3600) {
                //     $t4 = ceil($t / 7 / 24 / 3600);
                //     $topic[$k]['time_content'] = trans("message.周前", ['t' => $t4], $language);
                // } elseif ($t < 30 * 24 * 3600) {
                //     $t5 = ceil($t / 30 / 24 / 3600);
                //     $topic[$k]['time_content'] = trans("message.个月前", ['t' => $t5], $language);
                // } else {
                //     $topic[$k]['time_content'] = trans("message.年前", ['t' => 1], $language);
                // }
            }
        }

        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $topic), '');
        return formatData(['result' => 1, 'msg' => $topic]);


    }


    /**
     * Note - 检测是否可以创建贴子
     * DateTime 2024/7/22 11:58
     * User Admin
     * @param mixed $user
     */
    public function checkCreateStatus(mixed $user, $params)
    {
        $uid = $user['id'];
        // 审核环境不限制发布动态
        if ((new AppUpgradeDao())->isHideMaleChatCost(1, $params['version_code'], $params['channel'], FunUtil::getClientIp(), $uid)) {
            throw new MessageException('可以发布动态', CodeData::SUCCESS);
        }
        // 获取帖子信息
        $topic = Topic::query()->where('uid', $uid)->orderBy('time', 'desc')->first();
        // $topic = modelToArray($topic);
        if (!empty($topic)) {
            $topic = $topic->toArray();
            $settingData = SettingDao::getInstance()->getData();
            $intervalTime = $settingData['post_topic_interval'] ?? 0;
            if (time() - $topic['time'] < $intervalTime) {
                return formatData(['result' => 5, 'msg' => '您操作得太快了，请稍后再来发布动态吧~'], 200, CodeData::NEED_TIPS);
            }
        }
        return formatData(['result' => 1, 'msg' => '可以发布动态'], 200, CodeData::SUCCESS);
    }

    /**
     * Note - 创建帖子
     * DateTime 2024/7/22 16:18
     * User Admin
     * @param mixed $user
     * @param $params
     * @return array
     */
    public function createTopic(mixed $user, $params)
    {
        $content = $params['content'] ?? ''; // 动态内容
        $photo = $params['photo'] ?? ''; // 动态图片
        $show_type = $params['show_type'] ?? ''; // 0公开展示 1vip可见 2私密
        $tags = $params['tags'] ?? ''; // 标签ID（,分隔）
        $location = $params['location'] ?? ''; // 位置信息
        LoggerUtil::write('topic', [$photo]);

        $status = 0; //待审核
        $insertData = compact("content", 'photo', 'show_type', 'tags', 'location');
        $insertData['uid'] = $user['id'];
        $insertData['time'] = time();
        $insertData['publish_time'] = time();
        $insertData['reply_count'] = 0;
        $insertData['zan_count'] = 0;
        $insertData['is_show'] = 0;
        $insertData['status'] = $status;

        //添加
        $topicId = Topic::query()->insertGetId($insertData);

        if (empty($topicId)) {
            // $desc = '帖子发布失败!';
            // Tool::JSON(\CodeData::NEED_TIPS, array('result' => 4), $desc);
            return formatData(['result' => 4, 'msg' => '帖子发布失败'], 200, CodeData::NEED_TIPS);
        } else {
            MissionQueue::topic($user['id'], $user['sex']);

            if ($user['sex'] == 2) {
                AnchorSortLogDao::getInstance()->record($user['id'], 5, 1, '动态id：' . $topicId);
            }
            return formatData(['result' => 1, 'msg' => '发布成功，请等待审核'], 200, CodeData::SUCCESS);
        }

        // $tagsData = TopicTag::getAllTopicTagsCache(false);
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => array_values($tagsData)), '');
    }


    /**
     * Note - 帖子详情
     * DateTime 2024/7/22 17:02
     * User Admin
     * @param $userInfo
     * @param $params
     * @param $topic_id
     * @return array
     */
    public function getTopicDetail($userInfo, $params)
    {
        $topicReplyDao = TopicReplyDao::getInstance();
        $userDao = UserDao::getInstance();
        $topicDianZan = new TopicZan();
        $uid = $userInfo['id'];
        $topic_id = $params['topic_id'];

        // 获取帖子信息
        $topic = TopicDao::getInstance()->getTopicInfo($topic_id);
        $topic['reply_count'] = (int)$topic['reply_count'];
        $topic['zan_count'] = $topicDianZan->zanCount($topic['id'], 1);
        if (empty($topic)) {
            return formatData(['result' => 3], 200, CodeData::NEED_TIPS, '参数错误');
        }

        $topic['auth'] = [
            // 'real_card_status' => $topic['is_cardAuth']==1 ? 1 : 0,
            // 'real_img_status' => in_array($topic['is_faceAuth'] , [1,3]) ? 1 : 0,
            'real_education_status' => 0,
            'is_binding_phone' => $topic['is_binding']
        ];

        $topic['zan'] = $topicDianZan->getTopicZanUser($topic_id);

        foreach ($topic['zan'] as &$item) {
            if (!empty($item['head_image'])) {
                $item['head_image'] = AliyunOssHelper::compressImageHandle($item['head_image'], 100);
            }
        }

        // 获取帖子的回帖数据
        $reply = $topicReplyDao->getAllReply($topic_id, $params['page'], 20);
        if (!empty($reply)) {
            foreach ($reply as $key => $value) {
                $reply[$key]['head_image'] = FunUtil::formatHeadImg($value['head_image']);
                // 获取被回帖人的昵称
                $reply[$key]['reply_nickname'] = $value['nickname'];

                $reply[$key]['click'] = 0;
                $reply[$key]['is_click'] = 0;

                $reply[$key]['status'] = (int)$value['status'];
                $reply[$key]['time'] = (int)$value['time'];
                $reply[$key]['sex'] = (int)$value['sex'];
            }
        }

        $tease_arr = $userDao->readTease([$topic['uid']], $uid);
        $topic['is_tease'] = isset($tease_arr[$topic['uid']]) ? 1 : 0;

        if ($userInfo['sex'] == 1) {
            $c = ClosenessDao::read($uid, $topic['uid']);
        } else {
            $c = ClosenessDao::read($topic['uid'], $uid);
        }
        if ($c > 0) {
            $topic['is_tease'] = 1;
        }

        //获取帖子的点赞数/是否点赞
        $topic['click'] = $topic['zan_count'];
        $topic['is_click'] = $topic['is_zan'] = $topicDianZan->isZan($uid, $topic['id'], 1);

        // 计算帖子发布时间
        $topic['time_content'] = FunUtil::TopicPushTimeAgo($topic['publish_time'], Context::get('language'));

        // $time = time();
        // $t = (int)($time - (int)$topic['publish_time']);
        // if ($t < 3600) {
        //     $t1 = ceil($t / 60);
        //     $topic['time_content'] = $t1 . "分钟前";
        // } elseif ($t < 24 * 3600) {
        //     $t2 = ceil($t / 3600);
        //     $topic['time_content'] = $t2 . "小时前";
        // } elseif ($t < 7 * 24 * 3600) {
        //     $t3 = ceil($t / 24 / 3600);
        //     $topic['time_content'] = $t3 . "天前";
        // } elseif ($t < 21 * 24 * 3600) {
        //     $t4 = ceil($t / 7 / 24 / 3600);
        //     $topic['time_content'] = $t4 . "周前";
        // } elseif ($t < 30 * 24 * 3600) {
        //     $t5 = ceil($t / 30 / 24 / 3600);
        //     $topic['time_content'] = $t5 . "个月前";
        // } else {
        //     $topic['time_content'] = "1年前";
        // }


        $topic['sex'] = (int)$topic['sex'];
        if (!empty($topic['head_image'])) {
            $topic['head_image'] = FunUtil::formatHeadImg($topic['head_image']);
        }
        if (!empty($topic['photo'])) {
            $topic['photo'] = explode(',', $topic['photo']);
            foreach ($topic['photo'] as &$p) {
                $p = AliyunOssHelper::compressImageHandle($p, 1000);
            }
        }

        $topic['reply'] = !empty($reply) ? $reply : array();
        return formatData(['result' => 1, 'msg' => $topic]);
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $topic), '');
    }

    /**
     * Note - 删除帖子
     * DateTime 2024/7/22 17:02
     * User Admin
     * @param $uid
     * @param $topic_ids
     * @return array
     */
    public function delete($uid, $topic_ids)
    {
        $rt = Topic::query()->whereIn('id', $topic_ids)->where('uid', $uid)->update(['is_show' => 1]);
        return formatData(['result' => $rt]);

    }


}